<template>
    <div class="user-list-box">
        <div class="user-search-pat">
            <el-form ref="userSearchForm"
                     :model="userSearch"
                     label-width="80px"
                     :inline="true">
                <el-form-item label="用户名：">
                    <el-input v-model="userSearch.userName" placeholder="placeholder"></el-input>
                </el-form-item>
                <el-form-item label="邮箱：">
                    <el-input v-model="userSearch.email" placeholder="placeholder"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="doUserSearch()">查询</el-button>
                    <el-button type="primary" @click="resetUserSearchForm()">清空</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="list-box">
            <el-table
                v-loading="userListLoading"
                class="table-class"
                :data="users"
                style="width: 100%"
            >
                <el-table-column
                    fixed
                    prop="id"
                    label="ID"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="userName"
                    label="用户名"
                    width="100px">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="sign"
                    label="签名"
                    width="100">
                    <template slot-scope="scope">
                        <span v-text="scope.row.sign === null ? '无': scope.row.sign"></span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="avatar"
                    label="头像"
                    width="80">
                    <template slot-scope="scope">
                        <el-avatar :src="scope.row.avatar"></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="state"
                    label="状态"
                    width="80">
                    <template slot-scope="scope">
                        <div v-if="scope.row.state==='0'">
                            <el-tag type="danger">已删除</el-tag>
                        </div>
                        <div v-if="scope.row.state==='1'">
                            <el-tag type="danger">正常</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="state"
                    label="角色"
                    width="80">
                    <template slot-scope="scope">
                        <div v-if="scope.row.roles==='role_admin'">
                            <el-tag type="danger">管理员</el-tag>
                        </div>
                        <div v-if="scope.row.roles==='role_normal'">
                            <el-tag type="danger">游客</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="创建时间"
                    width="120">
                    <template slot-scope="scope">
                        <span v-text="formatDate(scope.row.createTime)"></span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="更新时间"
                    width="120">
                    <template slot-scope="scope">
                        <span v-text="formatDate(scope.row.updateTime)"></span>
                    </template>
                </el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="150">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="editUser(scope.row)">编辑</el-button>
                        <el-button type="danger"
                                   size="mini"
                                   @click="deleteItem(scope.row)"
                                   :disabled="scope.row.state==='0'">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="page-navigation-box">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNavigation.currentPage"
                :page-sizes="[5]"
                :page-size="pageNavigation.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageNavigation.totalElements">
            </el-pagination>
        </div>


        <div class="user-dialog-bix">
            <!--            删除用户的弹窗-->
            <el-dialog
                title="提示"
                :visible.sync="userDeleteDialogVisible"
                width="400px">
                <span>你确定要删除:{{ userDeleteMessage }} 这个用户吗?</span>
                <span slot="footer" class="dialog-footer">
                <el-button @click="userDeleteDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="doDeleteItem()">确 定</el-button>
              </span>
            </el-dialog>

            <!--            更新自己信息的弹窗-->
            <el-dialog
                @close="resetData"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :title="userEditTitle"
                :visible.sync="userEditorDialogVisible"
                width="45%">
                <div class="looper-editor-box">
                    <el-form ref="loopForm" :model="user" label-width="80px">
                        <el-form-item label="用户名">
                            <el-input v-model="user.userName" placeholder="用户名"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱地址">
                            <el-input v-model="user.email" placeholder="邮箱地址"></el-input>
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input v-model="user.password" placeholder="密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="签名">
                            <el-input v-model="user.sign" placeholder="签名"></el-input>
                        </el-form-item>
                        <el-form-item
                            label="状态">
                            <el-select v-model="user.state" placeholder="请选择分类状态">
                                <el-option
                                    label="正常"
                                    value="1">
                                </el-option>
                                <el-option
                                    label="禁用"
                                    value="0">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="头像上传">
                            <img v-if="user.avatar" :src="user.avatar" class="avatar-box" @click="toggleShow()">
                            <my-upload field="file"
                                       @crop-success="cropSuccess"
                                       @crop-upload-success="cropUploadSuccess"
                                       @crop-upload-fail="cropUploadFail"
                                       v-model="show"
                                       :width="300"
                                       :height="300"
                                       url="/admin/image/avatar"
                                       :params="params"
                                       :headers="headers"
                                       img-format="png">
                                <img :src="imgDataUrl">
                            </my-upload>
                        </el-form-item>
                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                <el-button @click="userEditorDialogVisible = false">取 消</el-button>
                <el-button type="primary"
                           @click="putUser()"
                >{{ this.userEditorBtnText }}
                </el-button>
                </span>
            </el-dialog>
        </div>
    </div>


</template>

<script>
import {success_code} from "@/utils/ResponseState";
import {formatDate} from "@/utils/date";
import {deleteUser, putUser, searchUsers} from "@/api/userApi";
import {hex_md5} from "@/utils/md5";
import myUpload from "vue-image-crop-upload";

export default {
    name: "manage-user",
    data() {
        return {
            // 显示的列表内容
            users: [],
            // 删除用户的dialog中的数据
            userDeleteDialogVisible: false,
            userDeleteMessage: "",
            userDeleteItemId: "",
            // 跟新用户的dialog中的数据
            userEditTitle: "添加",
            userEditorBtnText: "",
            userEditorDialogVisible: false,
            // 更新表单需要的数据对象
            user: {
                id: '',
                userName: '',
                password: '',
                email: '',
                avatar: '',
                roles: '',
                sign: '',
                order: 1,
                state: '1'
            },
            // 加载的flag
            userListLoading: false,
            // 分页需要的数据
            pageNavigation: {
                currentPage: 1,
                totalPages: 1,
                pageSize: 5,
                totalElements: 10
            },
            userSearch: {
                userName: '',
                email: ''
            },
            show: false,
            params: {
                token: '123456798',
                name: 'avatar'
            },
            headers: {
                smail: '*_~'
            },
            imgDataUrl: '' // the date base 64 url of created image
        }
    },
    components: {
        'my-upload': myUpload
    },
    methods: {
        // 点击编辑用户按钮的监听
        editUser(item) {
            // change data
            this.user.id = item.id;
            this.user.roles = item.roles;
            this.user.userName = item.userName;
            this.user.password = '';
            this.user.state = item.state;
            this.user.avatar = item.avatar;
            this.user.email = item.email;
            this.user.sign = item.sign;
            // change ui
            this.userEditorDialogVisible = true;
            this.userEditTitle = "更新用户信息"
            this.userEditorBtnText = "更 新"
        },
        // 点击删除用户按钮的监听
        deleteItem(item) {
            this.userDeleteDialogVisible = true;
            this.userDeleteMessage = item.userName;
            this.userDeleteItemId = item.id;
            // console.log(item);
        },
        // 删除用户
        doDeleteItem() {
            deleteUser(this.userDeleteItemId).then(result => {
                if (result.code === success_code) {
                    this.userListInitData();
                } else {
                    this.$message.error(result.message);
                }
            })

            this.userDeleteDialogVisible = false;
        },
        // 转换日期格式
        formatDate(dataStr) {
            let date = new Date(dataStr);
            return formatDate(date, "yyyy-MM-dd hh:mm:ss");
        },
        userListInitData() {
            this.userListLoading = true;

            this.handleCurrentChange(this.pageNavigation.currentPage);


            this.userListLoading = false;
        },
        // 更新用户信息
        putUser() {
            // check data
            if (this.user.email === "") {
                this.$message.warning("邮箱不能为空")
                return;
            } else {
                const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                if (!reg.test(this.user.email)) {
                    this.$message.warning("请输入有效的邮箱")
                    return;
                }
            }

            if (this.user.password !== "") {
                if (this.user.password.length < 6) {
                    this.$message.warning("新密码至少6位");
                    return;
                } else {
                    this.user.password = hex_md5(this.user.password);
                }
            }

            if (this.user.userName === "") {
                this.$message.warning("用户名不能为空");
                return;
            }
            if (this.user.id === "") {
                this.$message.warning("用户id不能为空");
                return;
            }


            putUser(this.user).then(result => {
                if (result.code === success_code) {
                    // change ui state
                    this.userListInitData()
                } else {
                    // change ui state
                    this.$message.error(result.message);
                }
            });

            this.resetData();
            this.userEditorDialogVisible = false
        }
        ,
        resetData() {
            this.user.id = '';
            this.user.userName = '';
            this.user.password = '';
            this.user.state = '1';
            this.user.sign = '';
            this.user.email = '';
            this.user.avatar = '';
        }
        ,
        handleClose(done) {
            console.log(done);
        }
        ,
        // 搜索用户 获取用户列表
        doUserSearch() {
            searchUsers(1, 5, this.userSearch.userName, this.userSearch.email).then(result => {
                if (result.code === success_code) {
                    this.$message.success(result.message);

                    this.users = result.data.content;
                } else {
                    this.$message.error(result.message);
                }
            })
        }
        ,
        // 清空用户搜索项
        resetUserSearchForm() {
            this.userSearch.userName = '';
            this.userSearch.email = '';
        }
        ,
        // 搜索页面大小改变的监听
        handleSizeChange(val) {
            this.pageNavigation.pageSize = val;
        }
        ,
        // 搜索页码改变的监听
        handleCurrentChange(val) {
            this.pageNavigation.currentPage = val;

            searchUsers(this.pageNavigation.currentPage,
                this.pageNavigation.pageSize,
                this.userSearch.userName,
                this.userSearch.email).then(result => {
                if (result.code === success_code) {
                    this.$message.success(result.message);
                    this.users = result.data.content;

                    this.pageNavigation.totalElements = result.data.totalElements;
                    this.pageNavigation.totalPages = result.data.totalPages;
                    this.pageNavigation.currentPage = result.data.number + 1;
                } else {
                    this.$message.error(result.message);
                }
            });
        },
        // 控制图片上传窗口的flag
        toggleShow() {
            this.show = !this.show;
        },
        /**
         * 打开图片成功
         *
         * [param] imgDataUrl
         * [param] field
         */
        cropSuccess(imgDataUrl, field) {
            console.log('-------- crop success --------');
            console.log(field);
            this.imgDataUrl = imgDataUrl;
        },
        /**
         * upload success
         * 上传图片成功
         *
         * [param] jsonData  server api return data, already json encode
         * [param] field
         */
        cropUploadSuccess(response) {
            if (response.code === success_code) {
                this.user.avatar = '/portal/image/' + response.data.path;
            } else {
                this.$message.error(response.message);
            }
        },
        /**
         * upload fail
         * 上传图片失败
         * [param] status    server api return error status, like 500
         * [param] field
         */
        cropUploadFail(status, field) {
            console.log('-------- upload fail --------');
            console.log(status);
            console.log('field: ' + field);
        }
    },
    // 生命周期函数 用于初始化
    mounted() {
        // init data
        this.userListInitData();
    }
}
</script>

<style scoped>
.avatar-box {
    width: 178px;
    height: 178px;
    border-radius: 50%;
    display: block;
}
</style>